﻿using HttpHelper;
using ICSharpCode.SharpZipLib.Zip;
using MicroTest.Properties;
using MicroTest_Client;
using Newtonsoft.Json.Linq;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MicroTest
{
   
    public partial class FrmStartNewExt : Form
    {
        
        public FrmStartNewExt()
        {

            TransparencyKey= Color.FromArgb(0, 0, 0, 0);
            InitializeComponent();
#if DEBUG
            //txtUserName.Text = "zxy111";
            //txtPassword.Text = "123456";
#endif

        }
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }
        private bool bEventHandler = false;
        public string TestKey = string.Empty;
        private LoginType loginType = LoginType.LT_NET;
        BackgroundWorker backgroundWorker = null;
        private string UserName = string.Empty;
        private List<GradeStruct> gradeInfos = new List<GradeStruct>();
        private List<ClassStruct> classInfos = new List<ClassStruct>();
        //private List<SubjectStruct> subjectInfos = new List<SubjectStruct>();
        //private List<ExamStruct> examInfos = new List<ExamStruct>();
        private List<LxcStruct> lxcInfos = new List<LxcStruct>();
        private List<ZjStruct> zjInfos = new List<ZjStruct>();
        private string SchoolInfo = string.Empty;
        private string GradeInfo = string.Empty;
        private string ClassInfo = string.Empty;
        private string ExamInfo = string.Empty;
        private string ExamID = string.Empty;
        private string selectedLXCID = string.Empty;
        private string selectedZJID = string.Empty;
        private string selectedClassID = string.Empty;
        private string selectedGradeID = string.Empty;
        private string selectedZJ = string.Empty;
        private string BasePageSerial = string.Empty;
        public SceneType EnterSceneType = SceneType.Scene_Class;
        private bool IsRememberPwd = false;
        private void tbKey_Enter(object sender, EventArgs e)
        {
            if (tbKey.Text == "请选择考试文件")
                tbKey.Text = "";
            tbKey.ForeColor = ColorTranslator.FromHtml("#333333");
        }

        private void tbKey_Leave(object sender, EventArgs e)
        {
            if (tbKey.Text == "")
                tbKey.Text = "请选择考试文件";
            tbKey.ForeColor = ColorTranslator.FromHtml("#aaaaaa");
        }

        private void tbKey_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
               // btnLogin_Click(sender, e);
            }
        }

        private void FrmStart_Load(object sender, EventArgs e)
        {
            LoadRememberAccountsConfig();
            transparentTabControl.MakeTransparent();
            transparentTabControl.Visible = false;
            //tbKey.Text = "F656905A-7710-4575-B24E-2D8791A075BF";
            lblVersion.Text = "v" + Application.ProductVersion;


            labInfoBJ.Top = labTitleMc.Bottom + 10;
            labBJ.Top = labInfoBJ.Top;

            btnConfirm.Top = labInfoBJ.Bottom + 28;
            btnReChoose.Left = btnConfirm.Right + 8;
            btnReChoose.Top = btnConfirm.Top;

            pnlInfo.Visible = false;

            backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += BackgroundWorker_DoWork;
            backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
            txtUserName.SelectedText = "";
            txtUserName_Leave(null, null);
            txtPassword_Leave(null, null);
        }
        private void SaveRememberAccountsConfig()
        {
            string dataFile = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\WiseClass";
            if (!Directory.Exists(dataFile))
            {
                Directory.CreateDirectory(dataFile);
            }
            string configFile = dataFile + "\\mtconfig.dat";
            if (File.Exists(configFile))
                File.Delete(configFile);
            if (!IsRememberPwd)
                return;
            FileStream fs = File.Open(configFile, FileMode.CreateNew);
            StreamWriter sw = new StreamWriter(fs);
            string accoutsAndPwdinfo = null;
            if (IsRememberPwd)
                accoutsAndPwdinfo = txtUserName.Text + "|" + txtPassword.Text;
            else
                accoutsAndPwdinfo = txtUserName.Text;
            sw.WriteLine(accoutsAndPwdinfo);
            sw.Close();
            fs.Close();

        }
        private void LoadRememberAccountsConfig()
        {
            string dataFile = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\WiseClass";
            if(!Directory.Exists(dataFile))
            {
                Directory.CreateDirectory(dataFile);
                IsRememberPwd = false;
                SetRememberPwdCheckStatus(false);
                return;
            }
            string configFile = dataFile + "\\mtconfig.dat";
            if (File.Exists(configFile) == false)
            {
                IsRememberPwd = false;
                SetRememberPwdCheckStatus(false);
                return;
            }
            FileStream fs = File.Open(configFile, FileMode.Open);
            StreamReader sw = new StreamReader(fs);
            string accountsAndPwd=sw.ReadLine();
            sw.Close();
            fs.Close();

            if (accountsAndPwd!=null)
            {
                string[] parts = accountsAndPwd.Split('|');
                txtUserName.Text = parts[0];
                txtUserName.HideSelection = true;
                if (parts.Length==2)
                {
                    txtPassword.PasswordChar = '*';
                    txtPassword.Text = parts[1];
                    //checkRember.Checked = true;
                    IsRememberPwd = true;
                    SetRememberPwdCheckStatus(true);

                }
                //textBox1.Text = "ddd";

            }
            else
            {
                IsRememberPwd = false;
                SetRememberPwdCheckStatus(false);

            }
        }
        private void SetRememberPwdCheckStatus(bool ischecked)
        {
            if (ischecked)
                picRember.Image = Resources.login_sel_on;
            else
                picRember.Image = Resources.login_sel_off;
        }
        private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            string queryString = string.Empty;
            NetWorkMissonParameter para = (NetWorkMissonParameter)e.Argument;
            NetCommunication net = new NetCommunication();
            string msg = string.Empty;
            bool ret = net.NetGetRequest(para.Parameter, ref msg);
            NetWorkMissonResult result = new NetWorkMissonResult();
            result.Success = ret;
            result.NMT = para.NMT;
            result.ReturnMessage = msg;
            if (para.NMT == NetMissonType.NMT_LOGIN && result.Success == true)
            {
                
                JObject ojb = JObject.Parse(msg);
                if (Convert.ToInt32(ojb["State"].ToString()) == 1)
                {
                    //年级
                    msg = string.Empty;
                    if (true == GetGradeList(txtUserName.Text, ref msg))
                    {
                        string errMsg = string.Empty; ;
                        if (false == ParseGradeList(msg, ref errMsg))
                        {
                            result.Success = false;
                            result.ReturnMessage = errMsg;
                            e.Result = result;
                            return;
                        }
                    }
                    else
                    {
                        result.Success = false;
                        result.ReturnMessage = msg;
                        return;
                    }
                    //班级
                    if (gradeInfos.Count != 0)
                    {
                        string usr = txtUserName.Text;
                        string njid = gradeInfos[0].GradeID.ToString();
                        msg = string.Empty;
                        //Program.MTInfo.MicroTestClassID=
                        if (true == GetClassList(usr, njid, ref msg))
                        {
                            string errMsg = string.Empty;
                            ParseClassList(msg, ref errMsg);
                        }
                    }
                    //学科
                    //msg = string.Empty;
                    //if(true==GetSubjectList(ref msg))
                    //{
                    //    string errMsg = string.Empty;
                    //    ParseSubjectList(msg, ref errMsg);
                    //}
                    //练习册列表
                    msg = string.Empty;
                    if (gradeInfos.Count != 0/*&&classInfos.Count!=0&&subjectInfos.Count!=0*/)
                    {
                        string usr = txtUserName.Text;
                        string njid = gradeInfos[0].GradeID.ToString();
                        Program.MTInfo.MicroTestUserName = usr;
                        Program.MTInfo.MicroTestGradeID = njid;
                        if (true == GetLxcList(usr, njid, ref msg))
                        {
                            string errMsg = string.Empty;
                            ParseLxcList(msg, ref errMsg);
                        }
                    }
                    msg = string.Empty;
                    if (lxcInfos.Count != 0/*&&classInfos.Count!=0&&subjectInfos.Count!=0*/)
                    {
                        string usr = txtUserName.Text;
                        string lxcid = lxcInfos[0].LxcID;
                        if (true == GetZjList(usr, lxcid, ref msg))
                        {
                            string errMsg = string.Empty;
                            ParseZjList(msg, ref errMsg);
                        }
                    }


                }
            }
            //Grade -> Class
            //Grade -> Lxc
            else if (para.NMT == NetMissonType.NMT_BJ && result.Success == true)
            {
                if (true)
                {
                    string errMsg = string.Empty;
                    if (false == ParseClassList(result.ReturnMessage, ref errMsg))
                    {
                        result.Success = false;
                        result.ReturnMessage = errMsg;
                        e.Result = result;
                    }
                    //string msgTmp = string.Empty;
                    //errMsg = string.Empty;
                    //if (true == GetLxcList(txtUserName.Text, selectedGradeID, ref msgTmp))
                    //{
                    //    ParseLxcList(msgTmp, ref errMsg);
                    //}
                }

            }
            //LXC -> ZJ
            else if (para.NMT == NetMissonType.NMT_ZJ && result.Success == true)
            {
                string errMsg = string.Empty;
                if (false == ParseZjList(result.ReturnMessage, ref errMsg))
                {
                    result.Success = false;
                    result.ReturnMessage = errMsg;
                    e.Result = result;
                    return;
                }
            }
            else if (para.NMT == NetMissonType.NMT_ST && result.Success == true)
            {
                string errMsg = string.Empty;
                if (false == ParseStudentList(result.ReturnMessage, ref errMsg))
                {
                    result.Success = false;
                    result.ReturnMessage = errMsg;
                    e.Result = result;
                    return;
                }

            }
            else if (para.NMT == NetMissonType.NMT_EXAM && result.Success == true)
            {
                string errMsg = string.Empty;
                if (false == ParseCreateExam(result.ReturnMessage, ref errMsg))
                {
                    result.Success = false;
                    result.ReturnMessage = errMsg;
                    e.Result = result;
                }

            }
            e.Result = result;
        }
        private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            NetWorkMissonResult result =(NetWorkMissonResult) e.Result;
            EnableControls(true);
            ELogger.Trace(string.Format("MissonComplete-->{0}  {1}", result.NMT, result.Success));
            switch (result.NMT)
            {
                case NetMissonType.NMT_LOGIN:
                    {

                        this.Cursor = System.Windows.Forms.Cursors.Arrow;
                        btnNetLogin.Enabled = true;
                        //lnkKSWJLonin.Enabled = true;
                        labClass.Enabled = true;
                        if (result.Success == false)
                        {
                            ShowLoginFailMessage(string.Format("登陆失败：{0}", result.ReturnMessage));

                            //MessageBox.Show(string.Format("登陆失败：{0}", result.ReturnMessage), "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            ELogger.Error(string.Format("登陆失败：{0}", result.ReturnMessage));
                        }
                        else
                        {
                            JObject obj = JObject.Parse(result.ReturnMessage);
                            if (obj["State"] != null && Convert.ToInt32(obj["State"].ToString()) == 1)
                            {


                                combGrade.Items.Clear();
                                combGrade.Items.AddRange(gradeInfos.ToArray());
                                if (gradeInfos.Count != 0)
                                    combGrade.SelectedIndex = 0;
                                combClass.Items.Clear();
                                combClass.Items.AddRange(classInfos.ToArray());
                                if (classInfos.Count != 0)
                                    combClass.SelectedIndex = 0;
                                combLxc.Items.Clear();
                                combLxc.Items.AddRange(lxcInfos.ToArray());
                                if (lxcInfos.Count != 0)
                                    combLxc.SelectedIndex = 0;
                                combZj.Items.Clear();
                                combZj.Items.AddRange(zjInfos.ToArray());
                                if (zjInfos.Count != 0)
                                    combZj.SelectedIndex = 0;
                                combGrade.SelectedIndexChanged += CombGrade_SelectedIndexChanged;
                                combClass.SelectedIndexChanged += CombClass_SelectedIndexChanged;
                                combLxc.SelectedIndexChanged += combLxc_SelectedIndexChanged;
                                combZj.SelectedIndexChanged += combZj_SelectedIndexChanged;
                                //combZj.DrawItem += CombZj_DrawItem;
                                //combZj.DropDownClosed += CombZj_DropDownClosed;
                                //combZj.DrawMode = DrawMode.OwnerDrawFixed;
                                bEventHandler = true;
                                UserName = txtUserName.Text;
                                pnlFirstLogon.Visible = false;
                                labTitle.Visible = false;
                                //pnlChooseMicroTest.Left = 0;
                                //pnlChooseMicroTest.Top = this.Height - pnlChooseMicroTest.Height;
                                pnlChooseMicroTest.Visible = true;
                                loginType = LoginType.LT_NET;
                                labSchool.Text = SchoolInfo;
                                labSchool.Left = (labSchool.Parent.Width - labSchool.Width) / 2;
                                transparentTabControl.SelectedIndex = 2;
                                SaveRememberAccountsConfig();
                                Program.CurrentClassInfo.Login = true;

                            }
                            else if (obj["State"] != null)
                            {
                                ShowLoginFailMessage(string.Format("登陆失败：{0}", obj["Message"].ToString()));
                                //MessageBox.Show(string.Format("登陆失败：{0}", obj["Message"].ToString()), "登陆失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                ELogger.Error(string.Format("登陆失败：{0}", obj["Message"].ToString()));
                            }
                            else
                            {
                                ShowLoginFailMessage(string.Format("登陆失败：未知错误"));

                                //MessageBox.Show(string.Format("登陆失败：未知错误"), "登陆失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                ELogger.Error("登陆失败：未知错误");
                            }
                        }
                    }
                    break;
                case NetMissonType.NMT_NJ:
                    break;
                case NetMissonType.NMT_BJ:
                    {
                        this.Cursor = System.Windows.Forms.Cursors.Arrow;
                        if (result.Success == false)
                        {
                            MessageBox.Show("获取班级列表失败！\n" + result.ReturnMessage);
                            ELogger.Trace("获取班级列表失败！" + result.ReturnMessage);
                        }
                        else
                        {

                            combClass.Items.Clear();
                            combClass.Items.AddRange(classInfos.ToArray());
                            combClass.SelectedIndex = combClass.Items.Count == 0 ? -1 : 0;

                            //combZj.Items.Clear();
                            //zjInfos.Clear();
                            //combLxc.Items.Clear();
                            //combLxc.Items.AddRange(lxcInfos.ToArray());

                            //combLxc.SelectedIndex = combLxc.Items.Count == 0 ? -1 : 0;
                        }
                    }
                    break;
                case NetMissonType.NMT_XK:
                    break;
                case NetMissonType.NMT_KS:
                    break;
                case NetMissonType.NMT_ST:
                    {
                        this.Cursor = System.Windows.Forms.Cursors.Arrow;
                        if (result.Success == false)
                        {
                            MessageBox.Show("获取学生列表失败！\n" + result.ReturnMessage);
                            ELogger.Error("获取学生列表失败！" + result.ReturnMessage);
                        }
                        else
                        {
                            
                            pnlInfo.Visible = true;
                            pnlChooseMicroTest.Visible = false;
                            //transparentTabControl.SelectedIndex = 3;
                            //this.Cursor = System.Windows.Forms.Cursors.Arrow;
                            this.DialogResult = DialogResult.OK;
                            this.Close();

                        }
                    }
                    break;
                case NetMissonType.NMT_LXC:
                    break;
                case NetMissonType.NMT_ZJ:
                    {
                        this.Cursor = System.Windows.Forms.Cursors.Arrow;
                        if (result.Success == false)
                        {
                            MessageBox.Show("获取章节列表失败！\n" + result.ReturnMessage);
                            ELogger.Trace("获取章节列表失败！" + result.ReturnMessage);
                        }
                        else
                        {
                            combZj.Items.Clear();
                            combZj.Items.AddRange(zjInfos.ToArray());
                            combZj.SelectedIndex = combZj.Items.Count == 0 ? -1 : 0;
                        }
                    }
                    break;
                case NetMissonType.NMT_EXAM:
                    {
                        
                        if (result.Success == false)
                        {
                            this.Cursor = System.Windows.Forms.Cursors.Arrow;
                            MessageBox.Show("创建考试失败！\n" + result.ReturnMessage);
                            ELogger.Trace("创建考试失败！" + result.ReturnMessage);
                        }
                        else
                        {
                            TestKey = Program.MTInfo.MicroTestID;
                            ELogger.Trace(string.Format("微测ID:{0}", TestKey));
                            ELogger.Trace(string.Format("学校信息：{0}", Program.MTInfo.MicroTestRoomInfo));
                            ELogger.Trace(string.Format("试卷名称:{0}", Program.MTInfo.MicroTestTitle));

                            string msgTmp = string.Empty;
                            if (true == GetPaperInfo(TestKey, ref msgTmp))
                            {
                                string errMsg = string.Empty;
                                if(ParsePaperInfo(msgTmp, ref errMsg))
                                {
                                    ELogger.Trace(string.Format("获取试卷基地址成功，基地址为：{0}", BasePageSerial));

                                    NetCommunication net = new NetCommunication();
                                    string dataFile = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\WiseClass\\img.zip";
                                    if (File.Exists(dataFile))
                                        File.Delete(dataFile);
                                    string msg = string.Empty;
                                    bool b=net.NetDownLoadRequest(string.Format("get?type=BKIMG&id={0}", TestKey), dataFile, ref msg);
                                    if(b==true)
                                    {
                                        ExtractBackgroundImages(dataFile);
                                        ELogger.Trace("获取试卷背景图片成功");
                                    }
                                    else
                                    {
                                        ELogger.Error("获取试卷背景图片失败");

                                    }
                                }
                                else
                                {
                                    ELogger.Error(string.Format("解析试卷基地址失败"));

                                }
                            }
                            else
                            {
                                ELogger.Error(string.Format("获取试卷基地址失败"));

                            }
                            this.Cursor = System.Windows.Forms.Cursors.Arrow;
                            this.DialogResult = DialogResult.OK;
                            this.Close();
                        }
                    }
                    break;
                default:
                    break;
            }


        }
        private void ShowLoginFailMessage(string msg)
        {
            pnlError.Width = pnlError.Parent.Width;
            timerTip.Start();
            labTip.Text = msg;
            labTip.Left = (pnlError.Width - labTip.Width) / 2;
            pnlError.Visible = true;
        }
        private string AddPageAddres(string basePage,int index)
        {
            string[] parts = basePage.Split('.');
            int section = Convert.ToInt32(parts[0]);
            int shelf = Convert.ToInt32(parts[1]);
            int book = Convert.ToInt32(parts[2]);
            int page = Convert.ToInt32(parts[3]);
            page += index;
            if(section==1713&&page>107)
            {
                book++;
                page -= 108;
                if(book>52)
                {
                    shelf++;
                    book = 0;
                }
            }
            if(section==1536&&page>107)
            {
                book++;
                page -= 108;
                if (book > 72)
                {
                    shelf++;
                    book = 0;
                }
            }
            return string.Format("{0}.{1}.{2}.{3}", section, shelf, book, page);
        }
        private bool ExtractBackgroundImages(string path)
        {
            string desFolder= Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\WiseClass";
            if (Directory.Exists(desFolder + "\\Images"))
                Directory.Delete(desFolder + "\\Images", true);
            try
            {
                FastZip zip = new FastZip();
                zip.ExtractZip(path, desFolder, "");
                // bunziped =ZipHelper.UnZip(path, desFolder);
            }
            catch (Exception ex)
            {
                ELogger.Error(string.Format("解压文件{0}失败，失败信息：{1}", path, ex.Message));
                return false;
            }
            
            desFolder = desFolder + "\\Images";
            DirectoryInfo di = new DirectoryInfo(desFolder);
            FileInfo[] fi = di.GetFiles();
            foreach (var item in fi)
            {
                string fileName = item.Name.Substring(0,item.Name.LastIndexOf('.'));
                string[] parts = fileName.Split('_');
                if(parts==null||parts.Length<3)
                {
                    ELogger.Error(string.Format("图片{0}文件名解析失败", fileName));
                    continue;
                }
                int index = Convert.ToInt32(parts[2])-1;
                if(string.IsNullOrEmpty(BasePageSerial))
                {
                    ELogger.Error("试卷基地址为空");
                    continue;
                }
                string pageSerial = AddPageAddres(BasePageSerial, index);
                string newBackgroundImagePath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\WiseClass\\Images\\" + pageSerial+".jpg";
                item.MoveTo(newBackgroundImagePath);
                Program.MTInfo.AddPaperPageImage(pageSerial, Image.FromFile(newBackgroundImagePath));
                ELogger.Trace(string.Format("添加地址为{0}的试卷图片", pageSerial));
            }
            return true;


        }
        private void CombZj_DropDownClosed(object sender, EventArgs e)
        {
            ComboBox com = sender as ComboBox;
            toolTipItem.Hide(com);
        }

        private void CombZj_DrawItem(object sender, DrawItemEventArgs e)
        {
            ComboBox cb = sender as ComboBox;
            if (cb.SelectedIndex == -1)
                return;
            
            // 绘制背景
            e.DrawBackground();
            //绘制列表项目
            e.Graphics.DrawString(cb.Items[e.Index].ToString(), e.Font, System.Drawing.Brushes.Black, e.Bounds);
            
            //将高亮的列表项目的文字传递到toolTip1(之前建立ToolTip的一个实例)
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
            {
                toolTipItem.Show(cb.Items[e.Index].ToString(), cb, e.Bounds.X + e.Bounds.Width, e.Bounds.Y + e.Bounds.Height);
                ELogger.Trace(string.Format("{0} {1}", e.Bounds.X, e.Bounds.Y));
            }
            e.DrawFocusRectangle();

        }

        private void CombExam_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (combZj.SelectedIndex == -1)
                return;
            ExamStruct es = (ExamStruct)combZj.SelectedItem;
            ELogger.Trace(string.Format("选择考试【{0}】,密钥【{1}】", es.ExamStr,es.ExamID));
        }

        private void CombSubject_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (combLxc.SelectedIndex == -1)
                return;
            ClassStruct cs = (ClassStruct)combClass.SelectedItem;

            NetWorkMissonParameter para = new NetWorkMissonParameter();
            para.NMT = NetMissonType.NMT_KS;
            GradeStruct gs = (GradeStruct)combGrade.SelectedItem;
            SubjectStruct ss = (SubjectStruct)combLxc.SelectedItem;
            ELogger.Trace(string.Format("选择学科【{0}】，对应年级【{1}】，班级【{2}】",ss.SubjectStr, gs.GradeStr, cs.ClassStr));
            string qString = string.Format("PaperList?username={0}&njid={1}&bjid={2}&xkid={3}", UserName, gs.GradeID, cs.ClassID, ss.SubjectID);
            para.Parameter = qString;
            //combClass.SelectedIndexChanged -= CombClass_SelectedIndexChanged;
            //combExam.SelectedIndexChanged -= CombExam_SelectedIndexChanged;
            if (!backgroundWorker.IsBusy)
            {
                EnableControls(false);
                this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                backgroundWorker.RunWorkerAsync(para);
            }
        }

        private void CombClass_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (combClass.SelectedIndex == -1)
                return;
            ClassStruct cs = (ClassStruct)combClass.SelectedItem;
           
            GradeStruct gs = (GradeStruct)combGrade.SelectedItem;
            //SubjectStruct ss = (SubjectStruct)combLxc.SelectedItem;
            ELogger.Trace(string.Format("选择班级【{0}】，对应年级【{1}】", cs.ClassStr, gs.GradeStr));
            //NetWorkMissonParameter para = new NetWorkMissonParameter();
            //para.NMT = NetMissonType.NMT_KS;
            //string qString = string.Format("PaperList?username={0}&njid={1}&bjid={2}&xkid={3}", UserName, gs.GradeID, cs.ClassID, ss.SubjectID);
            //para.Parameter = qString;
            ////combClass.SelectedIndexChanged -= CombClass_SelectedIndexChanged;
            ////combExam.SelectedIndexChanged -= CombExam_SelectedIndexChanged;
            //if (!backgroundWorker.IsBusy)
            //{
            //    EnableControls(false);
            //    this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
            //    backgroundWorker.RunWorkerAsync(para);
            //}
        }

        private void CombGrade_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (combGrade.SelectedIndex == -1)
                return;
            btnEnterScene.Focus();
           // return;
            GradeStruct gs = (GradeStruct)combGrade.SelectedItem;
            ELogger.Trace(string.Format("选择年级【{0}】", gs.GradeStr));
            NetWorkMissonParameter para = new NetWorkMissonParameter();
            para.NMT = NetMissonType.NMT_BJ;
            string qString = string.Format("BJList?username={0}&njid={1}", UserName, gs.GradeID);
            para.Parameter = qString;
            //combClass.SelectedIndexChanged -= CombClass_SelectedIndexChanged;
            //combExam.SelectedIndexChanged -= CombExam_SelectedIndexChanged;
            if (!backgroundWorker.IsBusy)
            {
                selectedGradeID = gs.GradeID.ToString();
                EnableControls(false);
                this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                backgroundWorker.RunWorkerAsync(para);
            }

        }
        private void EnableControls(bool enable)
        {
            combLxc.Enabled = enable;
            //combClass.Enabled = enable;
            //combGrade.Enabled = enable;
            combZj.Enabled = enable;
            btnEnterScene.Enabled = enable;
            btnConfirm.Enabled = enable;
            btnReChoose.Enabled = enable;
            lnkLogOut.Enabled = enable;
        }
        private bool GetGradeList(string userName, ref string msg)
        {
            string qString = string.Format("NJList?username={0}", userName);
            
            NetCommunication net = new NetCommunication();
            bool ret = net.NetGetRequest(qString, ref msg);
            return ret;
        }
        private bool ParseGradeList(string msg,ref string errMsg)
        {
            JObject gradeObj = JObject.Parse(msg);
            if (Convert.ToInt32(gradeObj["State"]) != 1)
            {
                errMsg = gradeObj["Message"].ToString();
                return false;
            }
            gradeInfos.Clear();
            SchoolInfo = gradeObj["ScName"].ToString();
            JArray gradeList = gradeObj["List"] as JArray;
            foreach (var item in gradeList)
            {
                int id = Convert.ToInt32(item["id"].ToString());
                string grade = item["name"].ToString();
                GradeStruct gs = new GradeStruct();
                gs.GradeID = id;
                gs.GradeStr = grade;
                gradeInfos.Add(gs);
            }
            return true;
        }
        private bool GetClassList(string userName,string gradeID, ref string msg)
        {
            string qString = string.Format("BJList?username={0}&njid={1}", userName,gradeID);

            NetCommunication net = new NetCommunication();
            bool ret = net.NetGetRequest(qString, ref msg);
            return ret;
        }
        private bool ParseClassList(string msg, ref string errMsg)
        {
            JObject gradeObj = JObject.Parse(msg);
            if (Convert.ToInt32(gradeObj["State"]) != 1)
            {
                errMsg = gradeObj["Message"].ToString();
                return false;
            }
            classInfos.Clear();
            JArray gradeList = gradeObj["List"] as JArray;
            foreach (var item in gradeList)
            {
                int id = Convert.ToInt32(item["id"].ToString());
                string name = item["name"].ToString();
                ClassStruct gs = new ClassStruct();
                gs.ClassID = id;
                gs.ClassStr = name;
                classInfos.Add(gs);
            }
            return true;
        }

        //private bool GetSubjectList( ref string msg)
        //{
        //    string qString = "XKList";

        //    NetCommunication net = new NetCommunication();
        //    bool ret = net.NetGetRequest(qString, ref msg);
        //    return ret;
        //}
        //private bool ParseSubjectList(string msg, ref string errMsg)
        //{
        //    JObject gradeObj = JObject.Parse(msg);
        //    if (Convert.ToInt32(gradeObj["State"]) != 1)
        //    {
        //        errMsg = gradeObj["Message"].ToString();
        //        return false;
        //    }
        //    subjectInfos.Clear();
        //    JArray gradeList = gradeObj["List"] as JArray;
        //    foreach (var item in gradeList)
        //    {
        //        int id = Convert.ToInt32(item["id"].ToString());
        //        string name = item["name"].ToString();
        //        SubjectStruct gs = new SubjectStruct();
        //        gs.SubjectID = id;
        //        gs.SubjectStr = name;
        //        subjectInfos.Add(gs);
        //    }
        //    return true;
        //}

        private bool GetExamList(string usr,string njid,string bjid,string xkid,ref string msg)
        {
            string qString = string.Format("PaperList?username={0}&njid={1}&bjid={2}&xkid={3}", usr, njid, bjid, xkid);

            NetCommunication net = new NetCommunication();
            bool ret = net.NetGetRequest(qString, ref msg);
            return ret;
        }
        //private bool ParseExamList(string msg, ref string errMsg)
        //{
        //    JObject gradeObj = JObject.Parse(msg);
        //    if (Convert.ToInt32(gradeObj["State"]) != 1)
        //    {
        //        errMsg = gradeObj["Message"].ToString();
        //        return false;
        //    }
        //    examInfos.Clear();
        //    JArray gradeList = gradeObj["List"] as JArray;
        //    foreach (var item in gradeList)
        //    {
        //        string id = item["id"].ToString().Trim();
        //        string name = item["name"].ToString();
        //        ExamStruct gs = new ExamStruct();
        //        gs.ExamID = id;
        //        gs.ExamStr = name;
        //        examInfos.Add(gs);
        //    }
        //    return true;
        //}

        private bool ParseStudentList(string msg,ref string errMsg)
        {
            JObject gradeObj = JObject.Parse(msg);
            if (Convert.ToInt32(gradeObj["State"]) != 1)
            {
                errMsg = gradeObj["Message"].ToString();
                return false;
            }
            Program.MTInfo.ClearStudentCard();
            JArray gradeList = gradeObj["List"] as JArray;
            int count = 0;
            string str = string.Empty;
            try
            {
                foreach (var item in gradeList)
                {
                    str = item.ToString();
                    string name = item["name"].ToString();
                    int X = Convert.ToInt32(item["X"].ToString());
                    int Y = Convert.ToInt32(item["Y"].ToString());
                    int Width = Convert.ToInt32(item["Width"].ToString());
                    int Height = Convert.ToInt32(item["Height"].ToString());
                    string pageID = item["Pageid"].ToString();
                    StudentCard stc = new StudentCard();
                    stc.Name = name;
                    stc.LeftBound = X;
                    stc.TopBound = Y;
                    stc.CardWidth = Width;
                    stc.CardHeight = Height;
                    stc.PageId = pageID;
                    Program.MTInfo.AddStudentCard(stc);
                    ELogger.Info(string.Format("解析学生名单，第{0}个学生：{1}", ++count, name));
                }
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
                ELogger.Error(string.Format("解析学生名单失败！解析失败的字符串：{0},失败信息：{1}", str, errMsg));
                return false;
            }
            
            ELogger.Info(string.Format("名单解析完毕，共{0}个学生", count));
            //Program.MTInfo.MicroTestID = ExamID;
            Program.MTInfo.MicroTestTitle = selectedZJ;
            Program.MTInfo.MicroTestRoomInfo= SchoolInfo + GradeInfo + ClassInfo;
            //labMC.Text = Program.MTInfo.MicroTestTitle;
            //labBJ.Text = Program.MTInfo.MicroTestRoomInfo;
            UpdateExamInfo(labMC, Program.MTInfo.MicroTestTitle);
            UpdateExamInfo(labBJ, Program.MTInfo.MicroTestRoomInfo);

            return true;
        }
        private void UpdateExamInfo(Label lab,string txt)
        {
            if(this.InvokeRequired)
            {
                Action<Label, string> ac = new Action<Label, string>(UpdateExamInfo);
                this.Invoke(ac, new object[] { lab, txt });
            }
            else
            {
                lab.Text = txt;
          
            }
        }
        private bool GetLxcList(string userName, string gradeID, ref string msg)
        {
            string qString = string.Format("LxcList?username={0}&njid={1}", userName, gradeID);

            NetCommunication net = new NetCommunication();
            bool ret = net.NetGetRequest(qString, ref msg);
            return ret;
        }
        private bool ParseLxcList(string msg, ref string errMsg)
        {
            JObject gradeObj = JObject.Parse(msg);
            if (Convert.ToInt32(gradeObj["State"]) != 1)
            {
                errMsg = gradeObj["Message"].ToString();
                return false;
            }
            lxcInfos.Clear();
            JArray lxcList = gradeObj["List"] as JArray;
            foreach (var item in lxcList)
            {
                string id = item["id"].ToString();
                string name = item["name"].ToString();
                LxcStruct ls = new LxcStruct();
                ls.LxcID = id;
                ls.LxcStr = name;
                lxcInfos.Add(ls);
            }
            return true;
        }

        private bool GetZjList(string userName, string lxcID, ref string msg)
        {
            string qString = string.Format("zjList?username={0}&lxcid={1}", userName, lxcID);

            NetCommunication net = new NetCommunication();
            bool ret = net.NetGetRequest(qString, ref msg);
            return ret;
        }
        private bool ParseZjList(string msg, ref string errMsg)
        {
            JObject gradeObj = JObject.Parse(msg);
            if (Convert.ToInt32(gradeObj["State"]) != 1)
            {
                errMsg = gradeObj["Message"].ToString();
                return false;
            }
            zjInfos.Clear();
            JArray zjList = gradeObj["List"] as JArray;
            foreach (var item in zjList)
            {
                string id = item["id"].ToString();
                string name = item["name"].ToString();
                ZjStruct zj = new ZjStruct();
                zj.ZjID = id;
                zj.ZjStr = name;
                zjInfos.Add(zj);
            }
            return true;
        }
        private bool GetPaperInfo(string examID, ref string msg)
        {
            string qString = string.Format("weiceinfo?weiceid={0}", examID);

            NetCommunication net = new NetCommunication();
            bool ret = net.NetGetRequest(qString, ref msg);
            return ret;
        }
        
        private bool ParsePaperInfo(string msg, ref string errMsg)
        {
            JObject paperObj = JObject.Parse(msg);
            if (Convert.ToInt32(paperObj["State"]) != 1)
            {
                errMsg = paperObj["Message"].ToString();
                return false;
            }
            BasePageSerial = paperObj["PageID"].ToString();

            return true;
        }
        private bool CreateExam(string userName,string njid,string bjid,string lxcid,string zjid, ref string msg)
        {
            string qString = string.Format("CreateExam?username={0}&njid={1}&bjid={2}&lxcid={3}&zjid={4}", userName, njid, bjid, lxcid, zjid);

            NetCommunication net = new NetCommunication();
            bool ret = net.NetGetRequest(qString, ref msg);
            return ret;
        }
        private bool ParseCreateExam(string msg,ref string errMsg)
        {
            JObject gradeObj = JObject.Parse(msg);
            if (Convert.ToInt32(gradeObj["State"]) != 1)
            {
                errMsg = gradeObj["Message"].ToString();
                return false;
            }
            zjInfos.Clear();
            JObject item = gradeObj["WeiCe"] as JObject;
            //foreach (var item in zjList)
            //{
                string id = item["id"].ToString();
                string name = item["name"].ToString();
                ExamID=id;
                ExamInfo = name;
            //}
            Program.MTInfo.MicroTestID = ExamID;
            ELogger.Trace(string.Format("创建考试成功!考试名【{0}】密钥【{1}】", ExamInfo, ExamID));
            return true;
        }

        const int WM_NCLBUTTONDOWN = 0xA1;
        const int HT_CAPTION = 0x2;
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

        // 窗体上鼠标按下时
        protected override void OnMouseDown(MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left & this.WindowState == FormWindowState.Normal)
            {
                // 移动窗体
                this.Capture = false;
                SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
            }
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            //TestKey = tbKey.Text;
            //LoadMicroTestInfo("e:\\data.xls");
            //this.DialogResult = DialogResult.OK;
            //this.Close();
            if (pnlSelect.Visible == false)
                return;
            if (File.Exists(tbKey.Text.Trim()) == false)

            {
                MessageBox.Show("文件不存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            btnLogin.Enabled = false;
            if(LoadMicroTestInfo(tbKey.Text.Trim()))
            {
                pnlSelect.Visible = false;
                labTitle.Visible = false;
                labMC.Text = Program.MTInfo.MicroTestTitle;
                labBJ.Text = Program.MTInfo.MicroTestRoomInfo;
                loginType = LoginType.LT_DOC;
                pnlInfo.Visible = true;

            }
            else
            {
                MessageBox.Show("错误", "解析数据文件失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            btnLogin.Enabled = true;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
        private bool LoadMicroTestInfo(string filePath)
        {

            IWorkbook workbook=null;
            string fileExt = Path.GetExtension(filePath);
            try
            {
                using (var file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {

                    if (fileExt == ".xls")
                    {
                        workbook = new HSSFWorkbook(file);
                    }
                    else if (fileExt == ".xlsx")
                    {
                        workbook = new XSSFWorkbook(file);
                    }
                    ISheet sheet = workbook.GetSheetAt(0);
                    int rowIndex = 0;
                    IRow row = sheet.GetRow(rowIndex++);
                    ICell cell = row.GetCell(0);
                    string TestRoom = row.GetCell(0).StringCellValue.Trim() + row.GetCell(1).StringCellValue.Trim() + row.GetCell(2).StringCellValue.Trim() + "班";
                    Program.MTInfo.MicroTestRoomInfo = TestRoom;
                    Program.MTInfo.MicroTestID = row.GetCell(3).StringCellValue.Trim();
                    Program.MTInfo.MicroTestTitle = row.GetCell(4).StringCellValue.Trim();
                    Program.TEST_KEY = Program.MTInfo.MicroTestID;
                    rowIndex++;
                    row = sheet.GetRow(rowIndex++);
                    int countIndex = 0;
                    while(row!=null)
                    {
                        StudentCard sc = new StudentCard();
                        sc.Name = row.GetCell(0).StringCellValue.Trim();
                        sc.LeftBound = Convert.ToInt32(row.GetCell(2).StringCellValue.Trim());
                        sc.TopBound = Convert.ToInt32(row.GetCell(3).StringCellValue.Trim());
                        sc.CardWidth = Convert.ToInt32(row.GetCell(4).StringCellValue.Trim());
                        sc.CardHeight = Convert.ToInt32(row.GetCell(5).StringCellValue.Trim());
                        sc.PageId = row.GetCell(7).StringCellValue.Trim();
                        Program.MTInfo.AddStudentCard(sc);
                        row = sheet.GetRow(rowIndex++);
                        ELogger.Trace(string.Format("解析学生名单，第{0}个学生：{1}", ++countIndex, sc.Name));
                    }
                    
                }
            }
            catch(Exception e)
            {
                ELogger.Error(string.Format("载入考试信息文件失败！{0}  {1}", e.Message, e.StackTrace));

                return false;
            }
            return true;
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            if (pnlSelect.Visible == true)
                return;
            if (loginType == LoginType.LT_DOC)
            {
                TestKey = Program.MTInfo.MicroTestID;
                ELogger.Trace(string.Format("微测ID:{0}", TestKey));
                ELogger.Trace(string.Format("学校信息：{0}", Program.MTInfo.MicroTestRoomInfo));
                ELogger.Trace(string.Format("试卷名称:{0}", Program.MTInfo.MicroTestTitle));
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                //创建考试！！！
                if (backgroundWorker.IsBusy)
                    return;
                this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                NetMissonType nty = NetMissonType.NMT_EXAM;
                NetWorkMissonParameter netWorkMissionPara = new NetWorkMissonParameter();
                netWorkMissionPara.NMT = nty;
                EnableControls(false);

                string queryString = string.Format("CreateExam?username={0}&njid={1}&bjid={2}&lxcid={3}&zjid={4}", UserName, selectedGradeID,selectedClassID,selectedLXCID,selectedZJID);
                netWorkMissionPara.Parameter = queryString;
                backgroundWorker.RunWorkerAsync(netWorkMissionPara);
            }
        }

        private void btnReChoose_Click(object sender, EventArgs e)
        {
            if (pnlSelect.Visible == true)
                return;
            if (LoginType.LT_DOC == loginType)
            {
                pnlInfo.Visible = false;
                pnlSelect.Visible = true;
                labTitle.Visible = true;
                transparentTabControl.SelectedIndex = 1;
            }
            else if(LoginType.LT_NET==loginType)
            {
                pnlInfo.Visible = false;
                pnlChooseMicroTest.Visible = true;
                transparentTabControl.SelectedIndex = 2;
            }
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            if (pnlSelect.Visible == false)
                return;
            if (DialogResult.OK==ofD.ShowDialog())
            {
                tbKey.Text = ofD.FileName;
                tbKey_Enter(null, null);
            }
        }

        private void labMC_Enter(object sender, EventArgs e)
        {
            toolTipKSMC.IsBalloon = true;
            toolTipKSMC.SetToolTip(this.labMC, labMC.Text);
        }

        private void labMC_MouseEnter(object sender, EventArgs e)
        {
            toolTipKSMC.IsBalloon = false;
            toolTipKSMC.SetToolTip(this.labMC, labMC.Text);
        }

        private void labBJ_MouseEnter(object sender, EventArgs e)
        {
            toolTipKSMC.IsBalloon = false;
            toolTipKSMC.SetToolTip(this.labBJ, labBJ.Text);
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void btnNetLogin_Click(object sender, EventArgs e)
        {
            
            if (btnNetLogin.Enabled == false || pnlFirstLogon.Visible == false)
                return;
            if (string.IsNullOrEmpty(txtUserName.Text) || string.IsNullOrEmpty(txtPassword.Text)
                ||txtUserName.Text=="用户名"
                ||txtPassword.Text=="密码"
                )
            {
                //MessageBox.Show("用户名密码不能为空！","维思课堂",MessageBoxButtons.OK,MessageBoxIcon.Information);
                ShowLoginFailMessage(string.Format("登陆失败：用户名密码不能为空！"));

                return;
            }
            ELogger.Trace("点击网络登陆按钮");
            ELogger.Trace(string.Format("用户【{0}】开始登录系统", txtUserName.Text));

            NetMissonType nty = NetMissonType.NMT_LOGIN;
            btnNetLogin.Enabled = false;
            //lnkKSWJLonin.Enabled = false;
            labClass.Enabled = false;
            NetWorkMissonParameter netWorkMissionPara = new NetWorkMissonParameter();
            netWorkMissionPara.NMT = nty;
            string usr = txtUserName.Text;
            string pwd = txtPassword.Text;
            string queryString = string.Format("login?username={0}&password={1}", usr, pwd);
            netWorkMissionPara.Parameter = queryString;
            backgroundWorker.RunWorkerAsync(netWorkMissionPara);
            this.Cursor = System.Windows.Forms.Cursors.WaitCursor;

        }

        private void label6_Click(object sender, EventArgs e)
        {

        }

        private void lnkKSWJLonin_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (pnlFirstLogon.Visible == false)
                return;
            pnlFirstLogon.Visible = false;
            pnlSelect.Visible = true;
            transparentTabControl.SelectedIndex = 1;

        }

        private bool LoadStudentBindList(string bindData)
        {

            if (File.Exists(bindData) == false)
            {
                ELogger.Trace("载入学生列表失败，学生列表不存在");
                return false;
            }
            object obj = SerializeHelper.DeserialData<StudentInfo>(bindData);
            if (obj != null)
            {
                Program.StudentInfo = (StudentInfo)obj;
                ELogger.Trace(string.Format("载入【{0}】学生绑定列表成功，共{1}个学生", Program.StudentInfo.Class, Program.StudentInfo.BandList.Count));

                return true;
            }
            ELogger.Trace("载入学生列表失败");

            return false;


        }
        private void btnEnterScene_Click(object sender, EventArgs e)
        {
            if (pnlChooseMicroTest.Visible == false)
                return;
            if (combClass.SelectedIndex == -1 ||
                combGrade.SelectedIndex == -1
               )
            {
                MessageBox.Show("班级信息不完整！");
                return;
            }
            if (backgroundWorker.IsBusy)
                return;

            GradeStruct gs = combGrade.SelectedItem as GradeStruct;
            ClassStruct cs = combClass.SelectedItem as ClassStruct;
            Program.MTInfo.MicroTestRoomInfo = SchoolInfo + gs.GradeStr + cs.ClassStr;
            Program.CurrentClassInfo.ClassRoomInfo= SchoolInfo + gs.GradeStr + cs.ClassStr;
            Program.MTInfo.MicroTestClassID = cs.ClassID.ToString();
            Program.MTInfo.MicroTestGradeID = gs.GradeID.ToString();
            ELogger.Trace(string.Format("用户选择【{0}】", Program.MTInfo.MicroTestRoomInfo));


            string folder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\WiseClass";
            if (!Directory.Exists(folder))
                Directory.CreateDirectory(folder);
            folder = folder + "\\BindInfo";
            if (!Directory.Exists(folder))
                Directory.CreateDirectory(folder);
            string bindData = string.Format("{0}\\{1}.cla", folder, Program.MTInfo.MicroTestRoomInfo);



            if (EnterSceneType==SceneType.Scene_Prepare)
            {
                ELogger.Trace("用户选择【备课】模式");
                bool bBind = LoadStudentBindList(bindData);
                //GradeStruct gs = combGrade.SelectedItem as GradeStruct;
                //ClassStruct cs = combClass.SelectedItem as ClassStruct;
                LoadStudentBindList(bindData);
                ZjStruct zj = combZj.SelectedItem as ZjStruct;
                LxcStruct lxc = combLxc.SelectedItem as LxcStruct;
                GradeInfo = gs.GradeStr;
                ClassInfo = cs.ClassStr;
                selectedClassID = cs.ClassID.ToString();
                selectedGradeID = gs.GradeID.ToString();
                ELogger.Trace(string.Format("开始下载学生名单，创建考试：{0} {1}", GradeInfo, ClassInfo));
                //StuList?username=zxy111&njid=13&bjid=1
                NetMissonType nty = NetMissonType.NMT_ST;
                NetWorkMissonParameter netWorkMissionPara = new NetWorkMissonParameter();
                netWorkMissionPara.NMT = nty;
                EnableControls(false);
                string queryString = string.Format("StuList?username={0}&njid={1}&bjid={2}", UserName, gs.GradeID, cs.ClassID);
                netWorkMissionPara.Parameter = queryString;
                backgroundWorker.RunWorkerAsync(netWorkMissionPara);
                this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                loginType = LoginType.LT_NET;
            }
            else if(EnterSceneType==SceneType.Scene_Class)
            {
                //MessageBox.Show("Coming soon...");
                //return;
                ELogger.Trace("用户选择【上课】模式");
                
                bool bBind = LoadStudentBindList(bindData);
                if (!bBind||Program.StudentInfo.BandList.Count == 0)
                {
                    //MessageBox.Show(string.Format("未检测到【{0}】学生绑定名单\n请先进入【备课】绑定学生名单！", Program.MTInfo.MicroTestRoomInfo), "维思课堂", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //ELogger.Trace("进入考试  未检测到学生绑定名单，请先绑定学生！");
                    //return;

                    //if (DialogResult.OK == MessageBox.Show(string.Format("未检测到【{0}】学生绑定名单\n是否请先进入【备课】绑定学生名单？", Program.MTInfo.MicroTestRoomInfo), "维思课堂", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                    if (DialogResult.OK == MessageBox.Show(string.Format("该班级学生无名单，即将转入签到功能"), "维思课堂", MessageBoxButtons.OKCancel, MessageBoxIcon.Information))

                    {
                        ELogger.Trace("进入上课  未检测到学生绑定名单，绑定学生！");
                        EnterSceneType = SceneType.Scene_ClassPrepare;
                        ZjStruct zj = combZj.SelectedItem as ZjStruct;
                        LxcStruct lxc = combLxc.SelectedItem as LxcStruct;
                        GradeInfo = gs.GradeStr;
                        ClassInfo = cs.ClassStr;
                        selectedClassID = cs.ClassID.ToString();
                        selectedGradeID = gs.GradeID.ToString();
                        ELogger.Trace(string.Format("开始下载学生名单，创建考试：{0} {1}", GradeInfo, ClassInfo));
                        //StuList?username=zxy111&njid=13&bjid=1
                        NetMissonType nty = NetMissonType.NMT_ST;
                        NetWorkMissonParameter netWorkMissionPara = new NetWorkMissonParameter();
                        netWorkMissionPara.NMT = nty;
                        EnableControls(false);
                        string queryString = string.Format("StuList?username={0}&njid={1}&bjid={2}", UserName, gs.GradeID, cs.ClassID);
                        netWorkMissionPara.Parameter = queryString;
                        backgroundWorker.RunWorkerAsync(netWorkMissionPara);
                        this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                        loginType = LoginType.LT_NET;
                    }

                }
                else
                {
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
               
                
                
            }
            else if(EnterSceneType==SceneType.Scene_Exam)
            {
                ELogger.Trace("用户选择【考试】模式");

                bool bBind = LoadStudentBindList(bindData);
               
                if (!bBind || Program.StudentInfo.BandList.Count == 0)
                {
                    //MessageBox.Show("未检测到学生绑定名单\n请先进入【备课】绑定学生名单！", "维思课堂", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //MessageBox.Show(string.Format("未检测到【{0}】学生绑定名单\n请先进入【备课】绑定学生名单！", Program.MTInfo.MicroTestRoomInfo), "维思课堂", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    //ELogger.Trace("进入考试  未检测到学生绑定名单，请先绑定学生！");
                    //return;
                    //if (DialogResult.OK == MessageBox.Show(string.Format("未检测到【{0}】学生绑定名单\n是否请先进入【备课】绑定学生名单？", Program.MTInfo.MicroTestRoomInfo), "维思课堂", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                    if (DialogResult.OK == MessageBox.Show(string.Format("该班级学生无名单，即将转入签到功能"), "维思课堂", MessageBoxButtons.OKCancel, MessageBoxIcon.Information))

                    {
                        ELogger.Trace("进入考试  未检测到学生绑定名单，绑定学生！");
                        EnterSceneType = SceneType.Scene_ExamPrepare;
                        ZjStruct zj = combZj.SelectedItem as ZjStruct;
                        LxcStruct lxc = combLxc.SelectedItem as LxcStruct;
                        GradeInfo = gs.GradeStr;
                        ClassInfo = cs.ClassStr;
                        selectedClassID = cs.ClassID.ToString();
                        selectedGradeID = gs.GradeID.ToString();
                        ELogger.Trace(string.Format("开始下载学生名单，创建考试：{0} {1}", GradeInfo, ClassInfo));
                        //StuList?username=zxy111&njid=13&bjid=1
                        NetMissonType nty = NetMissonType.NMT_ST;
                        NetWorkMissonParameter netWorkMissionPara = new NetWorkMissonParameter();
                        netWorkMissionPara.NMT = nty;
                        EnableControls(false);
                        string queryString = string.Format("StuList?username={0}&njid={1}&bjid={2}", UserName, gs.GradeID, cs.ClassID);
                        netWorkMissionPara.Parameter = queryString;
                        backgroundWorker.RunWorkerAsync(netWorkMissionPara);
                        this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                        loginType = LoginType.LT_NET;
                        //this.DialogResult = DialogResult.OK;
                        //this.Close();
                    }
                }
                else
                {
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }

                
            }
            

        }
        private void btnChooseMT_Click(object sender, EventArgs e)
        {
            if (pnlChooseMicroTest.Visible == false)
                return;
            if(combClass.SelectedIndex==-1||
                combGrade.SelectedIndex==-1||
                combLxc.SelectedIndex==-1||
                combZj.SelectedIndex==-1)
            {
                MessageBox.Show("考试信息不完整！");
                return;
            }
            if (backgroundWorker.IsBusy)
                return;

            GradeStruct gs = combGrade.SelectedItem as GradeStruct;
            ClassStruct cs = combClass.SelectedItem as ClassStruct;
            ZjStruct zj = combZj.SelectedItem as ZjStruct;
            LxcStruct lxc = combLxc.SelectedItem as LxcStruct;
            GradeInfo = gs.GradeStr;
            ClassInfo = cs.ClassStr;
            selectedLXCID = lxc.LxcID;
            selectedZJID = zj.ZjID;
            selectedZJ = zj.ZjStr;
            selectedClassID = cs.ClassID.ToString();
            selectedGradeID = gs.GradeID.ToString();
            ELogger.Trace(string.Format("确认考试，开始下载学生名单，创建考试：{0} {1}  {2} {3}", GradeInfo, ClassInfo, lxc.LxcStr, zj.ZjStr));
            //StuList?username=zxy111&njid=13&bjid=1
            NetMissonType nty = NetMissonType.NMT_ST;
            NetWorkMissonParameter netWorkMissionPara = new NetWorkMissonParameter();
            netWorkMissionPara.NMT = nty;
            EnableControls(false);
            string queryString = string.Format("StuList?username={0}&njid={1}&bjid={2}", UserName, gs.GradeID, cs.ClassID);
            netWorkMissionPara.Parameter = queryString;
            backgroundWorker.RunWorkerAsync(netWorkMissionPara);
            this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
            loginType = LoginType.LT_NET;
            
        }
        //练习册变化->章节变化
        private void combLxc_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (combLxc.SelectedIndex == -1)
                return;
            toolTipItem.SetToolTip(sender as ComboBox, ((sender as ComboBox).SelectedItem.ToString()));

            LxcStruct ls = (LxcStruct)combLxc.SelectedItem;
            NetWorkMissonParameter para = new NetWorkMissonParameter();
            para.NMT = NetMissonType.NMT_ZJ;
            GradeStruct gs = (GradeStruct)combGrade.SelectedItem;
            //SubjectStruct ss = (SubjectStruct)combLxc.SelectedItem;
            ELogger.Trace(string.Format("选择练习册【{0}】，对应年级【{1}】，学科【{2}】", ls.LxcStr, gs.GradeStr, "其它"));

            string qString = string.Format("zjList?username={0}&lxcid={1}", UserName,  ls.LxcID);
            para.Parameter = qString;
            if (!backgroundWorker.IsBusy)
            {
                EnableControls(false);
                this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                backgroundWorker.RunWorkerAsync(para);
            }
        }

        private void combZj_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (combZj.SelectedIndex == -1)
                return;
            toolTipItem.SetToolTip(sender as ComboBox,((sender as ComboBox).SelectedItem.ToString()));
            ZjStruct zj = (ZjStruct)combZj.SelectedItem;
            ClassStruct cs = (ClassStruct)combClass.SelectedItem;
            GradeStruct gs = (GradeStruct)combGrade.SelectedItem;
            LxcStruct lxc = (LxcStruct)combLxc.SelectedItem;
            string cla = cs == null ? "空" : cs.ClassStr;
            string gra = gs == null ? "空" : gs.GradeStr;
            string lx = lxc == null ? "空" : lxc.LxcStr;
            //SubjectStruct ss = (SubjectStruct)combLxc.SelectedItem;
            ELogger.Trace(string.Format("选择章节【{0}】，对应年级【{1}】，对应班级【{1}】，对应练习册【{1}】", zj.ZjStr, gra, cla, lx));
        }

        private void lnkLogOut_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (pnlChooseMicroTest.Visible == false)
                return;
            if (bEventHandler)
            {
                combGrade.SelectedIndexChanged -= CombGrade_SelectedIndexChanged;
                combClass.SelectedIndexChanged -= CombClass_SelectedIndexChanged;
                combLxc.SelectedIndexChanged -= combLxc_SelectedIndexChanged;
                combZj.SelectedIndexChanged -= combZj_SelectedIndexChanged;
            }
            pnlChooseMicroTest.Visible = false;
            pnlFirstLogon.Visible = true;
            labTitle.Visible = true;
            transparentTabControl.SelectedIndex = 0;
        }

        private void radioClass_CheckedChanged(object sender, EventArgs e)
        {
            if (radioClass.Checked)
                EnterSceneType = SceneType.Scene_Class;
        }

        private void radioExam_CheckedChanged(object sender, EventArgs e)
        {
            if (radioExam.Checked)
                EnterSceneType = SceneType.Scene_Exam;
        }

        private void radioBeike_CheckedChanged(object sender, EventArgs e)
        {
            if (radioBeike.Checked)
                EnterSceneType = SceneType.Scene_Prepare;
        }

        private void Panel_Paint(object sender, PaintEventArgs e)
        {
            Panel pan = sender as Panel;
            //ControlPaint.DrawBorder(e.Graphics,
            //                    pan.ClientRectangle,
            //                    Color.LightSeaGreen,//7f9db9
            //                    1,
            //                    ButtonBorderStyle.Solid,
            //                    Color.LightSeaGreen,
            //                    1,
            //                    ButtonBorderStyle.Solid,
            //                    Color.LightSeaGreen,
            //                    1,
            //                    ButtonBorderStyle.Solid,
            //                    Color.LightSeaGreen,
            //                    1,
            //                    ButtonBorderStyle.Solid);
            Color clr=Color.FromArgb(224, 236, 238);
            ControlPaint.DrawBorder(e.Graphics,
                                pan.ClientRectangle,
                                clr,//7f9db9
                                ButtonBorderStyle.Solid);

        }

        private void Remember_Click(object sender, EventArgs e)
        {
            IsRememberPwd = !IsRememberPwd;
            SetRememberPwdCheckStatus(IsRememberPwd);
        }

        private void labClass_Click(object sender, EventArgs e)
        {
            ELogger.Trace("用户选择直接登录");
            string folder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\WiseClass\\BindInfo";
            //return;
            //string bindData = string.Format("{0}\\{1}.cla", folder, Program.MTInfo.MicroTestRoomInfo);
            if(Directory.Exists(folder))
            {
                DirectoryInfo di = new DirectoryInfo(folder);
                FileInfo []files= di.GetFiles();
                List<ClassListInfo> list = new List<ClassListInfo>();
                foreach (var item in files)
                {
                    if (item.Name.EndsWith(".cla") == false)
                        continue;
                    ClassListInfo ci = new ClassListInfo()
                    {
                        Path = item.FullName,
                        ListInfo = item.Name.Substring(0, item.Name.Length - 4)
                    };
                    list.Add(ci);
                }
                combStudentList.Items.Clear();
                combStudentList.Items.AddRange(list.ToArray());
                if (combStudentList.Items.Count > 0)
                    combStudentList.SelectedIndex = 0;
            }

            transparentTabControl.SelectedIndex = 5;
            return;
            //if (Program.StudentInfo.BandList.Count == 0)
            //{
            //    MessageBox.Show("未检测到学生绑定名单\n无法直接上课！", "维思课堂", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    ELogger.Trace("未检测到学生绑定名单无法直接上课");
            //    return;
            //}
            //Program.CurrentClassInfo.Login = false;
            //EnterSceneType = SceneType.Scene_Class;
            //this.DialogResult = DialogResult.OK;
            //this.Close();
        }

        private void timerTip_Tick(object sender, EventArgs e)
        {
            timerTip.Stop();
            pnlError.Visible = false;
        }

        private void btnClass_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("敬请期待！");
            //return;
            if (backgroundWorker.IsBusy)
                return;
            EnterSceneType = SceneType.Scene_Class;
            btnEnterScene_Click(null, null);
        }

        private void btnExam_Click(object sender, EventArgs e)
        {
            if (backgroundWorker.IsBusy)
                return;
            EnterSceneType = SceneType.Scene_Exam;
            btnEnterScene_Click(null, null);

        }

        private void btnPrepare_Click(object sender, EventArgs e)
        {
            if (backgroundWorker.IsBusy)
                return;
            EnterSceneType = SceneType.Scene_Prepare;
            btnEnterScene_Click(null, null);

        }


       
        private void txtUserName_Enter(object sender, EventArgs e)
        {
            if(txtUserName.Text=="用户名")
                txtUserName.Text = "";
            txtUserName.ForeColor = ColorTranslator.FromHtml("#555555");
            txtUserName.TabStop = true;
            txtPassword.TabStop = true;
        }

        private void txtPassword_Enter(object sender, EventArgs e)
        {
            if (txtPassword.Text == "密码")
                txtPassword.Text = "";
            txtPassword.ForeColor = ColorTranslator.FromHtml("#555555");
            txtPassword.PasswordChar = '*';
            txtUserName.TabStop = true;
            txtPassword.TabStop = true;
        }

        private void txtUserName_Leave(object sender, EventArgs e)
        {
            if (txtUserName.Text == ""|| txtUserName.Text == "用户名")
            {
                txtUserName.Text = "用户名";
                txtUserName.ForeColor = ColorTranslator.FromHtml("#cccccc");
            }
        }

        private void txtPassword_Leave(object sender, EventArgs e)
        {
            if (txtPassword.Text == ""|| txtPassword.Text == "密码")
            {
                txtPassword.PasswordChar = '\0';
                txtPassword.Text = "密码";
                txtPassword.ForeColor = ColorTranslator.FromHtml("#cccccc");

            }

        }

        private void combGrade_DrawItem(object sender, DrawItemEventArgs e)
        {

            
            if(e.State.HasFlag(DrawItemState.ComboBoxEdit) || !e.State.HasFlag(DrawItemState.Focus))
            {
                e.Graphics.FillRectangle(Brushes.White, e.Bounds);
                e.Graphics.DrawString(combGrade.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Black), e.Bounds);
            }
            else //if(e.State.HasFlag(DrawItemState.Focus))
            {
                
                //e.DrawBackground();//133,221,218
                Color clrs = Color.FromArgb(133, 221, 218);
                e.Graphics.FillRectangle(new SolidBrush(clrs), e.Bounds);

                e.Graphics.DrawString(combGrade.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Black), e.Bounds);
                //toolTipKSMC.IsBalloon = true;
                if (Control.MousePosition.IsEmpty == false)
                {
                    int x = Control.MousePosition.X;
                    int y = Control.MousePosition.Y;
                    Point p = combGrade.PointToClient(new Point(x, y));
                    toolTipItem.Show(combGrade.Items[e.Index].ToString(), combGrade, e.Bounds.Width + 10, p.Y + e.Bounds.Height);

                }
                else
                    toolTipItem.Show(combGrade.Items[e.Index].ToString(), combGrade, e.Bounds.Width + 10, 0);

                //toolTipKSMC.SetToolTip(combGrade.Items[e.Index], labMC.Text);
            }

        }

        private void combClass_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index < 0)
                return;
            if (e.State.HasFlag(DrawItemState.ComboBoxEdit) || !e.State.HasFlag(DrawItemState.Focus))
            {
                e.Graphics.FillRectangle(Brushes.White, e.Bounds);
                e.Graphics.DrawString(combClass.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Black), e.Bounds);
            }
            else
            {
                //e.DrawBackground();
                Color clrs = Color.FromArgb(133, 221, 218);
                e.Graphics.FillRectangle(new SolidBrush(clrs), e.Bounds);

               // e.Graphics.DrawString(combGrade.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Black), e.Bounds);
                e.Graphics.DrawString(combClass.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Black), e.Bounds);
                
                if(Control.MousePosition.IsEmpty==false)
                {
                    int x = Control.MousePosition.X;
                    int y = Control.MousePosition.Y;
                    Point p=combClass.PointToClient(new Point(x, y));
                    toolTipItem.Show(combClass.Items[e.Index].ToString(), combClass, e.Bounds.Width + 10, p.Y+e.Bounds.Height);

                }
                else
                {
                    toolTipItem.Show(combClass.Items[e.Index].ToString(), combClass, e.Bounds.Width + 10, 0);

                }
                //Debug.WriteLine("{0} {1}", x, y);
            }
        }

        private void Comb_DropDownClosed(object sender, EventArgs e)
        {
            ComboBox com = sender as ComboBox;
            toolTipItem.Hide(com);
        }

        private void tabPage6_Click(object sender, EventArgs e)
        {

        }

        private void combStudentList_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index < 0)
                return;
            if (e.State.HasFlag(DrawItemState.ComboBoxEdit) || !e.State.HasFlag(DrawItemState.Focus))
            {
                e.Graphics.FillRectangle(Brushes.White, e.Bounds);
                e.Graphics.DrawString(combStudentList.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Black), e.Bounds);
            }
            else
            {
                //e.DrawBackground();
                Color clrs = Color.FromArgb(133, 221, 218);
                e.Graphics.FillRectangle(new SolidBrush(clrs), e.Bounds);
                e.Graphics.DrawString(combStudentList.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Black), e.Bounds);
                //toolTipKSMC.IsBalloon = true;
                if (Control.MousePosition.IsEmpty == false)
                {
                    int x = Control.MousePosition.X;
                    int y = Control.MousePosition.Y;
                    Point p = combStudentList.PointToClient(new Point(x, y));
                    toolTipItem.Show(combStudentList.Items[e.Index].ToString(), combStudentList, e.Bounds.Width + 10, p.Y + e.Bounds.Height);

                }
                else
                    toolTipItem.Show(combStudentList.Items[e.Index].ToString(), combStudentList, e.Bounds.Width + 10, 0);

                //toolTipKSMC.SetToolTip(combGrade.Items[e.Index], labMC.Text);
            }
        }

        private void combStudentList_DropDownClosed(object sender, EventArgs e)
        {
            ComboBox com = sender as ComboBox;
            toolTipItem.Hide(com);
        }

        private void btnDirectGoClass_Click(object sender, EventArgs e)
        {
            if (combStudentList.SelectedIndex == -1)
                return;
            ClassListInfo ci = combStudentList.SelectedItem as ClassListInfo;
            bool ret = LoadStudentBindList(ci.Path);
            if(!ret)
            {
                if(DialogResult.OK== MessageBox.Show("无效学生名单！是否删除？", "维思课堂", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    ELogger.Trace(string.Format("无效学生名单{0},删除",ci.Path));
                    File.Delete(ci.Path);
                }
                return;
            }
            ELogger.Trace(string.Format("加载{0}学生名单，直接上课", ci.Path));
            Program.CurrentClassInfo.Login = false;
            EnterSceneType = SceneType.Scene_Class;
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void btnBackFromDirectClass_Click(object sender, EventArgs e)
        {
            transparentTabControl.SelectedIndex = 0;
            ELogger.Trace("由选择已存在的学生列表界面返回到开始界面");
        }

        private void btnNetLogin_MouseEnter(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Hand;
        }

        private void btnNetLogin_MouseLeave(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Arrow;
        }

        private void labClass_MouseEnter(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Hand;
            labClass.ForeColor = Color.FromArgb(69,197,187);
            labClass.Font = new Font(labClass.Font, FontStyle.Bold);
        }

        private void labClass_MouseLeave(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Arrow;
            labClass.ForeColor = Color.FromArgb(146, 173, 191);
            labClass.Font = new Font(labClass.Font, FontStyle.Regular);

        }
    }
   
}
